<template>
  <view>
    <u-sticky>
      <u-navbar back-text=" " title="项目周报" :background="background" title-color="#ffffff" :custom-back="customBack" back-icon-color="#ffffff" ref="navbar" title-size="36"></u-navbar>
      <xmInfo
        :projectno="itemContent.projectno"
        :projectname="itemContent.projectname"
        ref="xmInfo"
        class="u-sticky"
      ></xmInfo>
    </u-sticky>
    <scroll-view
      scroll-y="true"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :scrolltolower-enabled="true"
      :refresher-triggered="triggered"
      @refresherrefresh="refresherrefresh"
      @scrolltoupper="refresherrefresh"
      class="scroll-view-class"
      :style="{ height: computedScrollViewHeight }"
    >
    <view
        class="scroll-content"
        ref="scrollContent"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        :style="{ height: computedScrollViewHeight  }"
      >
            <view v-for="(item,index) in list" class="cu-item shadow " style="position: relative;" :key="item.id">
              <view class="cu-form-group">
                <view style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;width: 40px;text-align: center;font-style: italic;font-weight: bold">
                  {{ index + 1 }}
                </view>
              </view>
              <view class="cu-form-group">
                <!-- <view class="text-xl text-bold">开始时间</view> -->
                <view class="text-xl text-bold">{{ item.starttime || "" }} <text style="margin: 0 10px;">至</text>  {{ item.endtime || "" }}</view>
              </view>
              <view class="cu-form-group">
                <view class="title">承包商</view>
                <view style="flex: 1;"> {{ item.contractor|| ""  }}</view>
              </view>
              <view class="cu-form-group">
                <view class="title">本周事项</view>
                <view style="flex: 1;" > {{ item.remarks|| ""  }}
				</view>
              </view>
              <view class="cu-form-group">
                <view class="title">填报信息</view>
                <view style="flex: 1;"> {{ item.createDate|| ""  }} （{{ item.createByName|| "" }}） </view>
              </view>
              <view class="cu-form-group" style="color:#3E97B0 ;"  @click="add(item.id)">
                <view class="content-footer-right">查看详情</view>
                <u-icon name="arrow-right"></u-icon>
              </view>
            </view>

            <view v-if="list.length" class="loadmore" style="justify-self: flex-end">
              <u-loadmore :status="loadStatus"></u-loadmore>
            </view>
            <u-empty v-if="!list.length" style="height: 100%;"></u-empty>
      </view>
    </scroll-view>
    <view class="btn-group cu-bar foot" v-if="flag">
      <button :disabled="projStatus=='5' || projStatus=='6' || projStatus=='7'?true:false" class="cu-btn bg-green shadow-blur" @tap="add()">
        <text class="cuIcon-add"></text> 创建
      </button>
    </view>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo },
  data() {
    return {
      background:{
        backgroundColor: '#3E97B0',
      },
      list: [],
      itemContent: {},
      query: {
        pageNo: 1,
        pageSize: 20,
        // orderBy: "a.create_date desc",
      },
      loadStatus: "loadmore",
      triggered: false,
      flag: hasPermission('app:proj:weekly:pmWeekly:edit'),
      scrollViewHeight: 0,
      headerHeight: 0,
	  projStatus:this.$store.state.auth.projStatus,
    };
  },
  onShow() {
    this.query.pageNo = 1;
    this.loadData();
  },
  onLoad(e) {
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        this.query.projectno = this.itemContent.projectno;
        this.query.projectname = this.itemContent.projectname;

        // this.loadData();
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
  },
  mounted() {
    this.$refs.xmInfo.$on('child-mounted-done', () => {
      this.calculateScrollViewHeight();
    });
  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
    },
  },
  methods: {
    customBack(){
      // 跳转到工作台页面
      // uni.navigateTo({
      //   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
      // });
	  uni.navigateBack({
	    delta: 1,
	  });
    },
    async calculateScrollViewHeight() {
      try {
    // 等待头部高度计算完成
          await new Promise((resolve) => {
            this.$nextTick(() => {
              this.headerHeight = this.$refs.xmInfo.$refs['u-sticky'].height + this.$refs.xmInfo.$refs['u-sticky'].h5NavHeight + this.$refs.navbar.navbarHeight;
              resolve();
            });
          });
          // 计算tabBar高度
		  if(this.flag){
            this.tabBarHeight = 80; // 假设tabbar高度为50px，实际应根据实际情况获取
          }else{
            this.tabBarHeight = 0; 
          }
          // 获取屏幕高度
          const systemInfo = uni.getSystemInfoSync();
          const screenHeight = systemInfo.windowHeight;
          console.log('screenHeight',this.headerHeight,this.$refs.xmInfo.$refs['u-sticky']);
          // 计算scroll-view高度
          this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
      } catch (error) {
        console.error('Error while calculating ScrollView height:', error);
      }
    },

    loadMore() {
      this.loadStatus = "loading";
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadData("add");
      }, 100);
    },
    loadData(type) {
      // 循环10次重复赋值
      this.$u.api.zfgs.weeklyPmWeeklyListData(this.query).then((res) => {
        if (res.list.length >= 0) {
          // this.xmList = res.list
          if (res.list.length < 20 || res.list.length == 0) {
            this.loadStatus = "nomore";
          }
          var data = res.list;          
          if (type == "add") {
            for (var i = 0; i < data.length; i++) {
              this.list.push(data[i]);
            }
          } else {
            this.list = data;
          }
        }
      });
    },
    async refresherrefresh() {
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadData();
      const scrollTop = 0
      uni.pageScrollTo({
            scrollTop,
            duration: 0,
      });     
      setTimeout(() => {
        this.triggered = false;
      }, 500);
  },

    add(id) {
      if (!!id) {
          uni.navigateTo({
              url: '/pages/zfgs/proj/weekly/pmWeekly/readOnlyForm?id='+id
          })
      } else {
        const xm = {
          projectno: this.itemContent.projectno,
          projectname: this.itemContent.projectname,
        };
        uni.navigateTo({
          url: "/pages/zfgs/proj/weekly/pmWeekly/form?xm=" + JSON.stringify(xm),
        });
      }
    },
  },
  beforeDestroy() {
    // 清理事件监听器
    try {
       this.$refs.xmInfo.$off('child-mounted-done');
     } catch (e) {
       console.log('Error while unbinding event:', e);
     }
  }
};
</script>
<style lang="scss" scoped>
.cu-bar {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
}
.cu-item {
  flex-wrap: wrap;
  padding: 8px 15px !important;
}

.title {
  width: 100px;
}
</style>